import { createReducer } from 'reduxsauce'
import { REHYDRATE } from 'redux-persist/es/constants'
import {
  GET_EXPERT_FEEDS,
  GET_EXPERT_SPECIAL_TOPIC,
  GET_EXPERT_BANNER,
  GET_POPULAR_SEARCH,
  GET_USER_MATCHED_TAGS,
  GET_EXPERT_GOODS,
  GET_EXPERT_TEMPLATES,
} from '@ACTIONS/expert'
import { ExpertStateITF } from '@REDUXITF/expert'

const INITIAL_STATE: ExpertStateITF = {
  feedList: [],
  loadingFeed: false,
  canLoadMore: true,
  specialTopic: [],
  homeBanner: [],
  popularSearch: [],
  tagIds: [],
  goods: [],
  templates: [],
}

const rehydrate = (state: ExpertStateITF, { payload }: { payload: { expert: ExpertStateITF } }) => {
  if (payload && payload.expert) {
    return { ...INITIAL_STATE, ...payload.expert }
  }
  return { ...state }
}
export default createReducer(INITIAL_STATE, {
  [REHYDRATE]: rehydrate,
  [GET_EXPERT_FEEDS.REQUEST]: (state, { payload = {} }) => {
    const { skip } = payload
    return {
      ...state,
      loadingFeed: true,
      feedList: skip === 0 ? [] : state.feedList,
    }
  },
  [GET_EXPERT_FEEDS.SUCCESS]: (state, { data: { FeedItems }, skip }) => {
    const { feedList } = state
    return {
      ...state,
      loadingFeed: false,
      feedList: skip === 0 ? FeedItems : [...feedList, ...FeedItems],
      canLoadMore: FeedItems.length >= 10,
    }
  },
  [GET_EXPERT_FEEDS.FAILURE]: (state, { error }) => ({
    ...state,
    loadingFeed: false,
    error,
  }),
  [GET_EXPERT_SPECIAL_TOPIC.SUCCESS]: (state, { data }) => ({
    ...state,
    specialTopic: data
  }),
  [GET_EXPERT_SPECIAL_TOPIC.FAILURE]: (state, { error }) => ({
    ...state,
    error,
  }),
  [GET_EXPERT_BANNER.SUCCESS]: (state, { data }) => ({
    ...state,
    homeBanner: data
  }),
  [GET_EXPERT_BANNER.FAILURE]: (state, { error }) => ({
    ...state,
    error,
  }),
  [GET_POPULAR_SEARCH.SUCCESS]: (state, { data }) => ({
    ...state,
    popularSearch: data
  }),
  [GET_POPULAR_SEARCH.FAILURE]: (state, { error }) => ({
    ...state,
    error,
  }),
  [GET_USER_MATCHED_TAGS.SUCCESS]: (state, { data }) => ({
    ...state,
    tagIds: data
  }),
  [GET_USER_MATCHED_TAGS.FAILURE]: (state, { error }) => ({
    ...state,
    error,
  }),
  [GET_EXPERT_GOODS.SUCCESS]: (state, { data }) => ({
    ...state,
    goods: data
  }),
  [GET_EXPERT_GOODS.FAILURE]: (state, { error }) => ({
    ...state,
    error,
  }),
  [GET_EXPERT_TEMPLATES.SUCCESS]: (state, { data }) => ({
    ...state,
    templates: data
  }),
  [GET_EXPERT_TEMPLATES.FAILURE]: (state, { error }) => ({
    ...state,
    error,
  }),
})
